﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IdentityModel.Tokens.Jwt;
using T.ApiResults;
using T.Settlement.Domain;
using T.Settlement.Domain.DTO;
using T.Settlement.Read.API.Application.Command.InvoiceCommand;

namespace T.Settlement.Read.API.Controllers
{
    /// <summary>
    /// 进/销项控制器(读)
    /// </summary>
    [Route("api/[controller]/[action]")]
    [Authorize]
    [ApiController]
    public class InvoiceController : ControllerBase
    {
        /// <summary>
        /// 进/销项
        /// </summary>
        private readonly IMediator _mediator;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="mediator"></param>
        public InvoiceController(IMediator mediator)
        {
            _mediator = mediator;
        }
        /// <summary>
        /// 显示进/销项
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<SListDTO<Invoice>>> Show([FromQuery] InvoiceShowCommand command)
        {
            ApiResult<SListDTO<Invoice>> result = new ApiResult<SListDTO<Invoice>>();
            try
            {
                command.CompanyID= HttpContext.User.FindFirst(JwtRegisteredClaimNames.Sid)?.Value;//获取公司Id,
                result.Data = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 返填进/销项
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<Invoice>> Backfill([FromQuery] InvoiceBackfillCommand command)
        {
            ApiResult<Invoice> result = new ApiResult<Invoice>();
            try
            {
                result.Data = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 导出进项发票excel
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportInputInvoiceExcel([FromQuery] InvoiceShowCommand command)
        {
            IWorkbook book = new XSSFWorkbook();
            ISheet sheet = book.CreateSheet();
            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("发票号");
            row.CreateCell(1).SetCellValue("开票单位");
            row.CreateCell(2).SetCellValue("发票类型");
            row.CreateCell(3).SetCellValue("发票金额");
            row.CreateCell(4).SetCellValue("税率");
            row.CreateCell(5).SetCellValue("税额");
            row.CreateCell(6).SetCellValue("开票日期");
            row.CreateCell(7).SetCellValue("制单人");
            row.CreateCell(8).SetCellValue("创建时间");

            var list = await _mediator.Send(command);
            int index = 1;
            foreach (var item in list.List)
            {
                row = sheet.CreateRow(index);
                row.CreateCell(0).SetCellValue(item.InvoiceNumber);
                row.CreateCell(1).SetCellValue(item.InvoicingUnit);
                row.CreateCell(2).SetCellValue(item.InvoiceType == 1 ? "普通发票" : "增值税发票");
                row.CreateCell(3).SetCellValue(Convert.ToInt32(item.InvoiceValue));
                row.CreateCell(4).SetCellValue(Convert.ToDouble(item.TaxRate) + "%");
                row.CreateCell(5).SetCellValue(Convert.ToInt32(Convert.ToDouble(item.InvoiceValue) * Convert.ToDouble(item.TaxRate)) * 0.01);
                row.CreateCell(6).SetCellValue(item.InvoicingDate.ToString());
                row.CreateCell(7).SetCellValue(item.InvoiceCreator);
                row.CreateCell(8).SetCellValue(item.CreatedDate.ToString());
                index++;
            }
            byte[] bytes = null;

            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                bytes = ms.ToArray();
            }
            string contentType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string fileName = "进项发票管理.xlsx";
            return File(bytes, contentType, fileName);
        }
        /// <summary>
        /// 导出进项发票excel
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportOutputInvoiceExcel([FromQuery] InvoiceShowCommand command)
        {
            IWorkbook book = new XSSFWorkbook();
            ISheet sheet = book.CreateSheet();
            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("发票号");
            row.CreateCell(1).SetCellValue("客户名称");
            row.CreateCell(2).SetCellValue("发票类型");
            row.CreateCell(3).SetCellValue("发票金额");
            row.CreateCell(4).SetCellValue("税率");
            row.CreateCell(5).SetCellValue("税额");
            row.CreateCell(6).SetCellValue("开票日期");
            row.CreateCell(7).SetCellValue("制单人");
            row.CreateCell(8).SetCellValue("创建时间");

            var list = await _mediator.Send(command);
            int index = 1;
            foreach (var item in list.List)
            {
                row = sheet.CreateRow(index);
                row.CreateCell(0).SetCellValue(item.InvoiceNumber);
                row.CreateCell(1).SetCellValue(item.CustomerName);
                row.CreateCell(2).SetCellValue(item.InvoiceType == 1 ? "普通发票" : "增值税发票");
                row.CreateCell(3).SetCellValue(Convert.ToInt32(item.InvoiceValue));
                row.CreateCell(4).SetCellValue(Convert.ToDouble(item.TaxRate) + "%");
                row.CreateCell(5).SetCellValue(Convert.ToInt32(Convert.ToDouble(item.InvoiceValue) * Convert.ToDouble(item.TaxRate)) * 0.01);
                row.CreateCell(6).SetCellValue(item.InvoicingDate.ToString());
                row.CreateCell(7).SetCellValue(item.InvoiceCreator);
                row.CreateCell(8).SetCellValue(item.CreatedDate.ToString());
                index++;
            }
            byte[] bytes = null;

            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                bytes = ms.ToArray();
            }
            string contentType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string fileName = "销项发票管理.xlsx";
            return File(bytes, contentType, fileName);
        }
    }
}
